#include <Klein/Shader/FragmentDatabase.h>
#include <Klein/Shader/Graph.h>
#include <Klein/Shader/GraphIdentifier.h>

Graph::Graph(const GraphIdentifier& identifier) :
	mIdentifier(identifier),
	mActivedNodeNumber(-1)
{
}

Graph::~Graph()
{
}

const GraphIdentifier& Graph::GetIdentifier() const
{
	return mIdentifier;
}

NodeRef Graph::CreateNode(const FragmentIdentifier& fragmentIdentifier)
{
	static int graphNoderNumber = 0;

	FragmentRef fragment = FragmentDatabase::GetReference().GetFragment(fragmentIdentifier);
	assert(fragment);

	NodeRef graphNode(new Node(fragment, graphNoderNumber));
	assert(graphNode);
	mGraphNumbersToNodes.insert(std::make_pair(graphNoderNumber, graphNode));

	graphNoderNumber += 1;

	return graphNode;
}

NodeRef Graph::GetNode(const int graphNodeNumber) const
{
	NodeRef graphNode;

	std::map<int, NodeRef>::const_iterator itr = mGraphNumbersToNodes.find(graphNodeNumber);
	if (itr != mGraphNumbersToNodes.end())
	{
		graphNode = itr->second;
	}

	return graphNode;
}

void Graph::CollectNodes(std::vector<NodeRef>& graphNodes)
{
	for (std::map<int, NodeRef>::const_iterator itr = mGraphNumbersToNodes.begin(); itr != mGraphNumbersToNodes.end(); ++ itr)
	{
		graphNodes.push_back(itr->second);
	}
}

void Graph::RemoveNode(const int graphNodeNumber)
{
	if (mGraphNumbersToNodes.find(graphNodeNumber) != mGraphNumbersToNodes.end())
	{
		mGraphNumbersToNodes.erase(graphNodeNumber);

		if (mActivedNodeNumber == graphNodeNumber)
		{
			mActivedNodeNumber = -1;
		}
	}
}

void Graph::ActiveNode(const int graphNodeNumber)
{
	assert(mGraphNumbersToNodes.find(graphNodeNumber) != mGraphNumbersToNodes.end());
	mActivedNodeNumber = graphNodeNumber;
}

int Graph::GetActivedNodeNumber() const
{
	return mActivedNodeNumber;
}
